package com.dk.conf;

import com.alibaba.druid.pool.DruidDataSource;
import com.dk.util.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class DruidDataSources {

    /**
     * master 加载到 spring 容器当中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.master")
    public DataSource masterDruid(){
        return new DruidDataSource();
    }

    /**
     * slave1 加载到 spring 容器当中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.slave1")
    public DataSource slave1Druid(){
        return new DruidDataSource();
    }

    /**
     * 把我们的数据源交给抽象的数据源
     */
    @Bean
    @Primary
    public DynamicDateSource dynamicDateSource(){
        DynamicDateSource dynamicDateSource = new DynamicDateSource();
        Map<Object,Object> map = new HashMap<>();
        map.put(DBUtil.MASTER,masterDruid());
        map.put(DBUtil.SLAVE1,slave1Druid());
        dynamicDateSource.setTargetDataSources(map);
        //如果没有指定数据源，使用这个默认的数据源
        dynamicDateSource.setDefaultTargetDataSource(masterDruid());
        return dynamicDateSource;
    }

}
